//
//  PersonCircleViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/8/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import LTScrollView
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class PersonCircleViewController: UIViewController {
    
    private lazy var collectionView: UICollectionView = {
        let H: CGFloat = view.bounds.height - 64
        let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: view.bounds.width, height: H), collectionViewLayout: getFlowLayout())
            collectionView.delegate = self
            collectionView.backgroundColor = UIColor.white
            collectionView.dataSource = self
        collectionView.register(UINib.init(nibName: "\(MessageCirclePersonalCenterCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(MessageCirclePersonalCenterCollectionViewCell.self)")
        
        return collectionView
    }()
    
    var isMine:Bool = false
    var userId:String?
    var page:Int = 1
    var totalPage:Int = 0
    var circleData:[CircleModel] = []
    
    let pageMaxCount = 16
    var pageCount = 0
    let messageCircleLRMargin: CGFloat = 27
    let messageCircleCellSize: CGFloat = {
        return (ScreenWidth - 40 - 10 * 3  - 27 * 2) / 4
    }()
    let messageCircleTBMargin: CGFloat = 18
    let messageCircleMargin: CGFloat = 24
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        view.addSubview(collectionView)
        glt_scrollView = collectionView
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        collectionView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        collectionView.mj_footer = footer
        
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        headerRefresh()
    }
    
    func showToast(msg :String) -> Void {
        self.view.makeToast("一度蜜：" + msg, duration: 1.5, position: .center)
    }
    
    /// 获取圈子列表
    func fetchCircleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(userCircleUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.circleData.removeAll()
                                            self.collectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.collectionView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = CircleModel(fromDic: dic)
                                            
                                            self.circleData.append(model)
                                        }
                                        if self.totalPage == self.circleData.count{
                                            self.collectionView.mj_footer=nil
                                        }
                                        else{
                                            self.collectionView.mj_footer = self.footer
                                        }
                                        self.collectionView.reloadData()
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.collectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.collectionView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.collectionView.mj_header.endRefreshing()
                                }
                                else{
                                    self.collectionView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }
}

extension PersonCircleViewController {
    
    // 顶部刷新
    @objc func headerRefresh(){
        page = 0
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        page += 1
        var parameters: [String: Any] = ["page":page,"pageSize":10,"type":1]
        if !self.isMine {
            parameters["userId"] = self.userId
        }
        self.fetchCircleList(parameters: parameters)
    }
    
    func getFlowLayout() -> UICollectionViewFlowLayout {
        var flowLayout = UICollectionViewFlowLayout()
        //一排显示四个,两排就是八个
        pageCount = 16
        while (pageCount % pageMaxCount != 0) {
            pageCount += 1;
        }
        
        flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: messageCircleCellSize, height: messageCircleCellSize * 1.5)
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10;
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        return flowLayout
    }
}


extension PersonCircleViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    // MARK: - CollectionViewDatasource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.circleData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(MessageCirclePersonalCenterCollectionViewCell.self)", for: indexPath) as! MessageCirclePersonalCenterCollectionViewCell
        cell.contentView.isHidden = indexPath.item > pageCount - (pageCount - 16)
        
        let model = self.circleData[indexPath.row]
        cell.showImageView.sd_setImage(with: appendUrl(suffix: model.coverPath!), completed: nil)
        cell.countLabel.text = model.circleName
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let messageCircleDetailVC = MessageCircleDetailViewController(nibName: "\(MessageCircleDetailViewController.self)", bundle: nil)
        let model: CircleModel? = self.circleData[indexPath.row]
        messageCircleDetailVC.titleLabel(text: (model?.circleName)!, nil)
        messageCircleDetailVC.showRightButtonType = .share
        messageCircleDetailVC.circieId = model?.id
        self.navigationController?.pushViewController(messageCircleDetailVC, animated: true)
    }
}
